var QueryForm; // 查询表单
var DetailAssetForm; // 资产详情表单
var addAssetForm;
var updateAssetForm;
var QueryWindow; // 查询窗口
var DeleteWindow;
var DetailAssetWindow; // 资产详细信息窗口
var AssetGridPanel, ZCDeleteGridPanel;
var AssetStore, ZCDeleteStore,SaveStore , AssetTypeStore; // 存放查询数据的表格的存贮变量
var selections, removeDelete; // 得到复选框选中的全部记录
var No='',Name='',Barcode='',State='',BelongTo='',Comment='',Sku='',DeviceType='';

//下拉列表级联
function changeValue() 
{ 
	if(addAssetForm.form.findField('AssetState').getValue()=='In') 
	{ 
		addAssetForm.form.findField('BelongTo').setValue('In'); 
	}
} 

var autoQuery = function() {
	AssetStore.removeAll();
	AssetStore.baseParams['start'] = '0';
	AssetStore.baseParams['limit'] = '20';
	
	AssetStore.baseParams['assetNo'] = No;
	
	AssetStore.baseParams['assetName']= Name;
	
	AssetStore.baseParams['assetBarcode'] = Barcode;
	
	AssetStore.baseParams['assetState'] = State;
	
	AssetStore.baseParams['belongTo'] = BelongTo;
	
	AssetStore.baseParams['comment'] = Comment;
	
	AssetStore.baseParams['sku']= Sku;
	
	AssetStore.baseParams['deviceType']= DeviceType;
	
	AssetStore.reload();
}


/*
 * 通过查询条件连接数据库得到数据
 * 
 */
var Query = function() {
/*	var StartTime = QueryForm.form.findField('StartUseTime').getRawValue();
	var EndTime = QueryForm.form.findField('EndUseTime').getRawValue();*/

	AssetStore.removeAll();
	
	AssetStore.baseParams['start'] = '0';
	AssetStore.baseParams['limit'] = '20';
	
	AssetStore.baseParams['assetNo'] = QueryForm.form.findField('AssetNo').getValue();
	No = QueryForm.form.findField('AssetNo').getValue();
	
	AssetStore.baseParams['assetName'] = QueryForm.form.findField('AssetName').getValue();
	Name = QueryForm.form.findField('AssetName').getValue();
	
	AssetStore.baseParams['assetBarcode'] = QueryForm.form.findField('AssetBarcode').getValue();
	Barcode = QueryForm.form.findField('AssetBarcode').getValue();
	
	AssetStore.baseParams['assetState'] = QueryForm.form.findField('AssetState').getValue();
	State = QueryForm.form.findField('AssetState').getValue();
	
	AssetStore.baseParams['belongTo'] = QueryForm.form.findField('BelongTo').getValue();
	BelongTo = QueryForm.form.findField('BelongTo').getValue();
	
	AssetStore.baseParams['comment'] = QueryForm.form.findField('Comment').getValue();
	Comment = QueryForm.form.findField('Comment').getValue();
	
	AssetStore.baseParams['sku']=QueryForm.form.findField('Sku').getValue();
	Sku = QueryForm.form.findField('Sku').getValue();
	
	AssetStore.baseParams['deviceType']=QueryForm.form.findField('DeviceType').getValue();
	DeviceType = QueryForm.form.findField('DeviceType').getValue();
	
	QueryWindow.hide();
	AssetGridPanel.getTopToolbar().items.get('type').setValue("");
	AssetStore.reload();
}

var DeleteZC = function() {
	var deleteAsset = ",";
	for (var i = 0; i < ZCDeleteStore.getCount(); i++) {
		var record = ZCDeleteStore.getAt(i);
		deleteAsset = deleteAsset + record.get('assetNo') + ",";
	}

	Ext.Ajax.request({
				url : '/Shrek/deleteAssetServlet',
				success : function(response, opts) {
//					insertUserLog(5);
					DeleteWindow.hide();
					var msg = Ext.decode(response.responseText).msg;
					alert(msg);
					AssetStore.reload();
					AssetTypeStore.reload();
				},
				failure : function() {
//					insertUserLog(6)
					alert('failed');
				},
				params : {
					assetNo : deleteAsset
				}
			});
}

var SaveZC = function(){
	                                     	var SaveRecord = new Ext.data.Record.create([{
	                                     				name : 'assetNo'
	                                     			}, {
	                                     				name : 'assetName'
	                                     			}, {
	                                     				name : 'assetBarcode'
	                                     			}, {
	                                     				name : 'assetState'
	                                     			}, {
	                                     				name : 'belongTo'
	                                     			}, {
	                                     				name : 'comment'
	                                     			},	{
	                                     				name : 'sku'
	                                     			}, {
	                                     				name : 'deviceType'
	                                     			}
	                                     			]);
var theReader = new Ext.data.JsonReader({
		totalProperty : 'total',
			root : 'result'
		}, SaveRecord);
	                                     	SaveStore = new Ext.data.Store({
	                                     				proxy : new Ext.data.HttpProxy({
	                                     							url : '/Shrek/selectAssetServlet'
	                                     						}),
	                                     				reader : theReader
	                                     			});
	
	
//	alert(AssetStore.getTotalCount());
	SaveStore.baseParams['limit'] = AssetStore.getTotalCount();	
	
//	AssetStore.removeAll();
	
	SaveStore.baseParams['start'] = '0';
//	AssetStore.baseParams['limit'] = '10000';
	
//	alert(No);
	SaveStore.baseParams['assetNo'] = No;
	
//	alert(Name);
	SaveStore.baseParams['assetName'] = Name;
	
//	alert(Barcode);
	SaveStore.baseParams['assetBarcode'] = Barcode;
	
//	alert(State);
	SaveStore.baseParams['assetState'] = State;

//	alert(BelongTo);
	SaveStore.baseParams['belongTo'] = BelongTo;
	
//	alert(Comment);
	SaveStore.baseParams['comment'] = Comment;
	
//	alert(Sku);
	SaveStore.baseParams['sku'] = Sku;
	
//	alert(DeviceType);
	SaveStore.baseParams['deviceType'] = DeviceType;
	
	
	SaveStore.reload({callback : function() {
//        alert(SaveStore.getCount());
    	var SaveAsset= ",";
    	for(var i = 0; i < SaveStore.getCount(); i++) {
    		var record = SaveStore.getAt(i);
    		SaveAsset = SaveAsset + record.get('assetNo') + ",";
    	}
    		Ext.Ajax.request({
				url : '/Shrek/saveAssetServlet',
				success : function(response, opts) {
					if(Ext.decode(response.responseText).msg=='succeed')
					{
						var ProgressBar = new Ext.ProgressBar({
							text : 'Export to Excel...',
							width : 300,
							applyTo:'save'
						});
						ProgressBar.wait({
							duration : 1000,
							interval : 100,
							increment : 10,
							text : 'working...',
							scope : this,
							fn : function(){
								var filename = 'ShrekAppleManagement_';
								filename += new Date().format('ymd');
//								alert(myDate);							
								window.location = '/Shrek/'+filename+'.xls';
								ProgressBar.hide();}
						});
					}
					else
					{
						alert(Ext.decode(response.responseText).msg);
					}
				},
				failure : function() {
//						insertUserLog(8)
						alert('failed');
					},
				params : {
					assetNo : SaveAsset
					}
				});
    	}
     });
//	alert(SaveStore.getCount());
}

//扫描功能，保留接口，供以后扩展
var ScanZC = function(){
	Ext.MessageBox.wait('scaning','扫描中，请稍后...');
	Ext.Ajax.request({
				url : '/Shrek/scanAssetServlet',
				success : function(response, opts)
				{
					Ext.MessageBox.hide();
					var msg = Ext.decode(response.responseText).msg;
//					alert(msg);
					
					if(msg=='开始扫描')
					{
/*						var barcode = Ext.decode(response.responseText).barcode;
						alert(barcode);
						addAssetWindow.show();
						addAssetForm.form.findField('AssetBarcode').setValue(barcode);*/
						alert('开始扫描....待扩展');
						
					}
					
				},
				failure : function()
				{
					alert('扫描失败');
				}
		});		
}


var AccessDBtoDelete = function() {
	var length = removeDelete.length;

	for (var i = 0; i < length; i++) {
		var record = removeDelete[0];
		ZCDeleteStore.remove(record);
	}
}
var DeleteSelectedAsset = function() {
	BuildDeleteZCGrid();
	BuildDeleteWindow();

	var length = selections.length;

	for (var i = 0; i < length; i++) {
		var record = selections[i];
		ZCDeleteStore.add(record);
	}

	DeleteWindow.show();
}

/*
 * 建立存放资产信息的布局
 */
var BuildAssetGrid = function() {
	var SelectModel = new Ext.grid.CheckboxSelectionModel({
		listeners : {
			selectionchange : function(sm) {
				selections = AssetGridPanel.getSelectionModel().getSelections();

				if (sm.getCount()) {
					AssetGridPanel.removeButton.enable();
					AssetGridPanel.updateButton.enable();
					AssetGridPanel.changeButton.enable();
				} else {
					AssetGridPanel.removeButton.disable();
					AssetGridPanel.updateButton.disable();
					AssetGridPanel.changeButton.disable();
				}
			}
		}
			// 单选
			// singleSelect:true
	});

	var AssetColumnModel = new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer(), SelectModel, {
				header : 'ID',
				sortable : true,
				dataIndex : 'assetNo'
			}, {
				header : 'ProductName',
				sortable : true,
				dataIndex : 'assetName'
			}, {
				header : 'SN',
				sortable : true,
				dataIndex : 'assetBarcode'
			}, {
				header : 'Status',
				sortable : true,
				dataIndex : 'assetState'
			}, {
				header : 'BelongTo',
				sortable : true,
				dataIndex : 'belongTo'
			}, {
				header : 'SKU',
				sortable : true,
				dataIndex : 'sku'
			}, {
				header : 'Comment',
				sortable : true,
				dataIndex : 'comment'
			}, {
				header : 'DeviceType',
				sortable : true,
				dataIndex : 'deviceType'
			}/*, {
				header : '折旧率',
				sortable : true,
				dataIndex : 'depreciation'
			}, {
				header : '资产状态',
				sortable : true,
				dataIndex : 'state'
			}*/]);
	var AssetRecord = new Ext.data.Record.create([{
				name : 'assetNo'
			}, {
				name : 'assetName'
			}, {
				name : 'assetBarcode'
			}, {
				name : 'assetState'
			}, {
				name : 'belongTo'
			}, {
				name : 'comment'
			},	{
				name : 'sku'
			}, {
				name : 'deviceType'
			}
			]);

	AssetStore = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : '/Shrek/selectAssetServlet'
						}),
				reader : new Ext.data.JsonReader({
							totalProperty : 'total',
							root : 'result'
						}, AssetRecord)
			});

	AssetTypeStore = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
			url : '/Shrek/getAssetType'	
		}),
		reader : new Ext.data.JsonReader({
			root : 'type'	
		},['type']),
		autoLoad : true									
});
	
	AssetGridPanel = new Ext.grid.GridPanel({
				title : 'Query the asset information(Prompt：~^0^~Double click the items if you need to view the details~^0^~)',
				width : '100%',
				height : 500,
				layout : 'fit',
				store : AssetStore,
				cm : AssetColumnModel,
				sm : SelectModel,
				stripeRows : true,
				loadMask : true,
				viewConfig : {
					forceFit : true
				},
				plugins : new Ext.ux.PanelResizer({
							minHeight : 100
						}),
				tbar : [{
							iconCls : 'add',
							id : 'add',
							tooltip : 'add a record',
							text : 'Add',
							handler : function() {
								addAssetWindow.show();
								getAssetNo();
								// Ext.getCmp('delete').hide();
								// AssetColumnModel.setHidden(1, true);
							}
						}, '-', {
							iconCls : 'delete',
							id : 'delete',
							tooltip : 'delete record(s)',
							text : 'Delete',
							ref : '../removeButton',
							disabled : true,
							handler : DeleteSelectedAsset
						}, '-', {
							iconCls : 'edit',
							id : 'edit',
							text : 'Modify',
							ref : '../updateButton',
							disabled : true,
							tooltip : 'modify a record',
							handler : function() {
								if (selections.length > 1) {
									alert("Please choose only one record");
									SelectModel.clearSelections();
								} else {
									for (var i = 0; i < selections.length; i++) {

										var record = selections[i];
										changesAssetWindow.show();
										updateAssetForm.getForm()
												.loadRecord(record);
									}
								}
							}
						}, '-', {
							iconCls : 'query',
							text : 'Query',
							tooltip : 'query the asset information',
							handler : function() {
								QueryWindow.show();
							}
						}, '-', {
							iconCls : 'save',
							id : 'save',
							text : 'Export',
							tooltip : 'export to the query result to excel',
							ref : '../saveButton',
							handler : SaveZC
						}, '-', {
							iconCls : 'empty',
							id : 'change',
							text : 'Lending/Returning',
							tooltip : 'change the status',
							ref : '../changeButton',
							disabled : true,
							handler : function() {
								if (selections.length > 1) {
									alert("Please choose only one record");
									SelectModel.clearSelections();
								} else {
									for (var i = 0; i < selections.length; i++) {

										var record = selections[i].get('assetNo');
										Ext.Ajax.request({
											url : '/Shrek/changeAssetServlet',
											success : function(response, opts)
											{
												var msg = Ext.decode(response.responseText).msg;
//												alert(msg);
												if(msg=='Out')//借出
												{
													insertUserLog(1,record);
													InputWindow.show();
													InputForm.form.findField('assetNo').setValue(record);
													
												}
												else if(msg=='In')//归还
												{
													insertUserLog(2,record);
													Ext.Ajax.request({
														url : '/Shrek/updataAssetBelongToServlet',
														success : function(response, opts) {
															AssetStore.reload();
														},
														failure : function() {
//															insertUserLog(6)
															alert('failed');
														},
														params : {
															assetNo : record,
															belongTo : 'In'
														}
													});
													
												}
												AssetStore.reload();
											},
											failure : function()
											{
												alert('failed');
											},
											params : 
											{
												changeRecord : record
											}
										});
									}
								}

							}
						}, '-', {
							iconCls : 'nav',
							id : 'scan',
							text : '扫描',
							tooltip : '开始扫描',
							handler : ScanZC
						}, '->',{
							iconCls : 'plugin',
							id : 'type',
							xtype : 'combo',
/*							store : new Ext.data.SimpleStore({
									fields : ['text'],
									data : [['7800'], ['DBlack'],['Apple'],['All']]
								}),*/
							store : AssetTypeStore,
							emptyText : 'Please choose...',
							mode : 'remote',
							triggerAction : 'all',
							valueField : 'type',
							displayField : 'type',
							readOnly : true,
							editable : true,
							listeners : {
							select:function(){
									AssetStore.removeAll();
									DeviceType = AssetGridPanel.getTopToolbar().items.get('type').getValue();
									if(DeviceType == 'All')
									{
										DeviceType = '';
									}
									AssetStore.baseParams['deviceType'] = DeviceType;
									AssetStore.reload();
								}
						}
						}],
				bbar : new Ext.PagingToolbar({
							pageSize : 20,
							store : AssetStore,
							displayInfo : true,
							displayMsg:'Displaying {0} - {1} of {2}',
							emptyMsg : 'No data to display',
							plugins : new Ext.ux.ProgressBarPager()/*,
							bufferResize : true*/
						})
			});

	AssetGridPanel.addListener('rowdblclick', function(AssetGridPanel,
			rowIndex, event) // 将AssetGridPanel的数据加载到UpdataFormPanel中
			{
				var record = AssetGridPanel.getStore().getAt(rowIndex);
				DetailAssetWindow.show();
				DetailAssetForm.getForm().loadRecord(record);
			});
}

var BuildDeleteZCGrid = function() {
	var SelectModel = new Ext.grid.CheckboxSelectionModel({
				listeners : {
					selectionchange : function(sm) {
						removeDelete = ZCDeleteGridPanel.getSelectionModel()
							 	.getSelections();

						if (sm.getCount()) {
							ZCDeleteGridPanel.removeButton.enable();
//							DeleteWindow.getEl('ok').enable(); 
						} else {
							ZCDeleteGridPanel.removeButton.disable();
//							DeleteWindow.getEl('ok').disable(); 
						}
					}
				}
			});

	var AssetColumnModel = new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer(),SelectModel, {
				header : 'ID',
				sortable : true,
				dataIndex : 'assetNo'
			}, {
				header : 'ProductName',
				sortable : true,
				dataIndex : 'assetName'
			}, {
				header : 'SN',
				sortable : true,
				dataIndex : 'assetBarcode'
			}, {
				header : 'Status',
				sortable : true,
				dataIndex : 'assetState'
			}, {
				header : 'BelongTo',
				sortable : true,
				dataIndex : 'belongTo'
			}, {
				header : 'SKU',
				sortable : true,
				dataIndex : 'sku'
			}, {
				header : 'Comment',
				sortable : true,
				dataIndex : 'comment'
			}, {
				header : 'DeviceType',
				sortable : true,
				dataIndex : 'deviceType'
			}]);

	var AssetRecord = new Ext.data.Record.create([{
				name : 'assetNo'
			}, {
				name : 'assetName'
			}, {
				name : 'assetBarcode'
			}, {
				name : 'assetState'
			}, {
				name : 'belongTo'
			}, {
				name : 'sku'
			}, {
				name : 'comment'
			}, {
				name : 'deviceType'
			}]);

	ZCDeleteStore = new Ext.data.Store({
				proxy : new Ext.data.MemoryProxy(),
				reader : new Ext.data.ArrayReader({}, AssetRecord)
			});

	ZCDeleteGridPanel = new Ext.grid.GridPanel({
				width : '100%',
				autoHeight : true,
				store : ZCDeleteStore,
				cm : AssetColumnModel,
				sm : SelectModel,
				stripeRows : true,
				loadMask : true,
				tbar : ['->', {
							iconCls : 'delete',
							tooltip : 'Remove the records you have choose to delete',
							text : 'Remove',
							ref : '../removeButton',
							disabled : true,
							handler : AccessDBtoDelete
						}]
			});
};
// var BuildUpdateAssetForm = function()
{
	updateAssetForm = new Ext.form.FormPanel({
		frame : true,
		labelAlign : 'right',
		labelWidht : 60,
		items : [{
			layout : 'column',
			items : [{
				columnWidth: 1.0,
				layout : 'form',
				xtype: 'fieldset',
				title: 'Asset Information',
				autoHeight : true,
				defaults : {
					width : 220,
					allowBlank : false
				},
				defaultType : 'textfield',
				items : [{
						fieldLabel : 'ID',
						name : 'assetNo',
						readOnly : true
					}, {
						fieldLabel : 'ProductName',
						name : 'assetName'
					}, {
						fieldLabel : 'SN',
						name : 'assetBarcode'
					},{
						fieldLabel : 'Status',
						name : 'assetState',
						xtype : 'combo',
						store : new Ext.data.SimpleStore({
							fields : ['text'],
							data : [/*['In'], ['Out'],*/ ['Broken']]
						}),
						emptyText : 'Please choose...',
						mode : 'local',
						triggerAction : 'all',
						valueField : 'text',
						displayField : 'text',
						readOnly : true,
						editable : false
					},{
						fieldLabel : 'BelongTo',
						name : 'belongTo',
						emptyText : 'Please input the name or In'
					}, {
						fieldLabel : 'SKU',
						name : 'sku'
					}, {
						fieldLabel : 'Comment',
						name : 'comment',
						allowBlank : true
					}, {
						fieldLabel : 'DeviceType',
						name : 'deviceType'
					}]
				}]
		}]
	});
};
// var BuildAddAssetForm = function()
{
	addAssetForm = new Ext.form.FormPanel({
		frame : true,
		labelAlign : 'right',
		labelWidht : 60,
		items : [{
			layout : 'column',
			items : [{
				columnWidth : 1.0,
				layout : 'form',
				xtype : 'fieldset',
				title : 'Asset Information',
				autoHeight : true,
				defaults : {
					width : 220,
					allowBlank : false
				},
				defaultType : 'textfield',
				items : [{
							fieldLabel : 'ID',
							name : 'AssetNo',
							readOnly : true
						}, {
							fieldLabel : 'ProductName',
							name : 'AssetName'
						}, {
							fieldLabel : 'SN',
							name : 'AssetBarcode'
						},{
							fieldLabel : 'Status',
							name : 'AssetState',
							xtype : 'combo',
							store : new Ext.data.SimpleStore({
									fields : ['text'],
									data : [['In'], /*['借出'],*/ ['Broken']]
								}),
							emptyText : 'Please choose...',
							mode : 'local',
							triggerAction : 'all',
							valueField : 'text',
							displayField : 'text',
							readOnly : true,
							editable : false,
							listeners : { select:function(){changeValue();}}
						},{
							fieldLabel : 'BelongTo',
							name : 'BelongTo',
							emptyText : 'Please input the name or In'
						}, {
							fieldLabel : 'SKU',
							name : 'Sku'
						}, {
							fieldLabel : 'Comment',
							name : 'Comment',
							allowBlank : true
						},{
							fieldLabel : 'DeviceType',
							name : 'DeviceType'
						}]
			}]
		}]
	});
};
/*
 * 双击表格行的时候存放资产详细信息的布局
 */
var BuildDetailAssetForm = function() {
	DetailAssetForm = new Ext.form.FormPanel({
				frame : true,
				labelAlign : 'right',
				labelWidht : 60,
				items : [{
					columnWidth : 1.0,
					layout : 'form',
					xtype : 'fieldset',
					title : 'Asset Information',
					autoHeight : true,
					defaults : {
						width : 220,
						disabled : true
					},
					defaultType : 'textfield',
					items : [{
								fieldLabel : 'ID',
								name : 'assetNo',
								readOnly : true
							}, {
								fieldLabel : 'ProductName',
								name : 'assetName'
							}, {
								fieldLabel : 'SN',
								name : 'assetBarcode'
							},{
								fieldLabel : 'Status',
								name : 'assetState',
							},{
								fieldLabel : 'BelongTo',
								name : 'belongTo',
							}, {
								fieldLabel : 'SKU',
								name : 'sku'
							}, {
								fieldLabel : 'Comment',
								name : 'comment'
							}, {
								fieldLabel : 'DeviceType',
								name : 'deviceType'
							}]
						}]
			})
}

/*
 * 建立查询资产信息的布局
 */
var BuildQueryForm = function() {
	QueryForm = new Ext.form.FormPanel({
		labelAlign : 'right',
		labelWidth : 70,
		width : '100%',
		bodyStyle : 'padding:20px 10px;',
		items : [{
			layout : 'column',
			border : false,
			items : [{
				bodyStyle : 'padding-top:5px',
				columnWidth : .5,
				layout : 'form',
				defaults : {
					width : 130
				},
				defaultType : 'textfield',
				items : [{
							fieldLabel : 'ID',
							name : 'AssetNo'
						},{
							fieldLabel : 'ProductName',
							name : 'AssetName'
						},{
							fieldLabel : 'SN',
							name : 'AssetBarcode'
						},{
							fieldLabel : 'SKU',
							name : 'Sku'
						}]
			}, {
				bodyStyle : 'padding-top:5px',
				columnWidth : .5,
				style : 'margin-left: 15px;',
				layout : 'form',
				defaults : {
					width : 130
				},
				defaultType : 'textfield',
				items : [{
							fieldLabel : 'Status',
							name : 'AssetState',
							xtype : 'combo',
							store : new Ext.data.SimpleStore({
										fields : ['text'],
										data : [['In'], ['Out'], ['Broken']]
									}),
							emptyText : 'Please choose...',
							mode : 'local',
							triggerAction : 'all',
							valueField : 'text',
							displayField : 'text',
							readOnly : true
						},{
							fieldLabel : 'BelongTo',
							name : 'BelongTo',
							/*xtype : 'combo',
							store : new Ext.data.SimpleStore({
										fields : ['text'],
										data : [['Liberty'], ['借者'], ['Liberty']]
									}),
							emptyText : '请选择',
							mode : 'local',
							triggerAction : 'all',
							valueField : 'text',
							displayField : 'text',
							readOnly : true*/
						},{
							fieldLabel : 'Comment',
							name : 'Comment'
						},{
							fieldLabel : 'DeviceType',
							name : 'DeviceType'
						}]
			}]
		}]
	})
}

/*
 * 建立查询资产信息的窗口 --- 存放QueryForm
 */
var BuildQueryWindow = function() {
	QueryWindow = new Ext.Window({
				title : '~ Query Window ~',
				width : 500,
				heigth : 400,
				modal : true,
				resizable : false,
				closeAction : 'hide',
				items : [QueryForm],
				keys : [{
				    	  	key: [10,13],
				    	  	fn:Query
				        }],
				buttons : [{
							iconCls : 'query',
							text : 'Query',
							handler : Query
						}, {
							iconCls : 'empty',
							text : 'Empty',
							handler : function() {
								QueryForm.getForm().reset();
							}
						}],
				buttonAlign : 'center'
			})
}

/*
 * 建立存放详细资产信息的布局
 */
var BuildDetailAssetWindow = function() {
	DetailAssetWindow = new Ext.Window({
				title : '~ Details(read only) ~',
				width : 400,
				height : 320,
				modal : true,
				resizable : false,
				closeAction : 'hide',
				items : [DetailAssetForm],
				buttons : [{
							iconCls : 'back',
							text : 'Return',
							handler : function() {
								DetailAssetWindow.hide();
							}
						}]
			})
}
var BuildDeleteWindow = function() {
	DeleteWindow = new Ext.Window({
				title : '~ Delete Window~',
				modal : true,
				width : 870,
				heigth : 300,
				closeAction : 'hide',
				resizable : true,
				items : [ZCDeleteGridPanel],
				buttons : [{
							iconCls : 'ok',
							text : 'Save',
							handler : DeleteZC
						}, {
							iconCls : 'cancel',
							text : 'Return',
							handler : function() {
								DeleteWindow.hide();
							}
						}],
				buttonAlign : 'left'
			})
}
var BuildLayout = function() {
	new Ext.Viewport({
				layout : 'border',
				items : [{
							region : 'center',
							layout : 'fit',
							items : [AssetGridPanel]
						}]
			})
};
var addAssetWindow = new Ext.Window({
			title : '~ Add Window ~',
			width : 400,
			height : 320,
			modal : true,
			resizable : true,
			closeAction : 'hide',
			items : [addAssetForm],
			buttons : [{
				iconCls : 'save',
				text : 'Save',
				handler : function() {
					if (!addAssetForm.getForm().isValid()) {
						return;
					} else {
//						var StartTime = addAssetForm.form
//								.findField('StartUseTime').getRawValue();
//						var produceDate = addAssetForm.form
//								.findField('ProduceDate').getRawValue();
//						if (produceDate > StartTime) {
//							alert('生产日期应该小于启用时间');
//							addAssetForm.form.findField('StartUseTime')
//									.setValue('');
//							addAssetForm.form.findField('ProduceDate')
//									.setValue('');
//							return;
//						}
						addAssetForm.getForm().submit({
							waitMsg : 'Adding.....',
							url : '/Shrek/addAssetServlet', // 提交数据到数据库
							success : function(f, action) {
								addAssetWindow.hide();
								if (action.result.success) {
									alert(action.result.msg);
									addAssetForm.getForm().reset();
//									getAssetNo();
//									addAssetForm.form.findField('AssetNo')
//											.setValue(assetNo);
//									insertUserLog(1); // 增加资产信息成功后，记录用户日志
//									alert('增加成功');
									AssetStore.reload();
									AssetTypeStore.reload();
								} 
								else
									alert(action.result.msg);
									//insertUserLog(2);
							}
						})
					}
				}
			}, {
				iconCls : 'empty',
				text : 'Empty',
				handler : function() {
					addAssetForm.getForm().reset();
					addAssetForm.form.findField('AssetNo').setValue(assetNo);
				}
			}, {
				iconCls : 'back',
				text : 'Return',
				handler : function() {
					addAssetWindow.hide();
				}
			}],
			buttonAlign : 'right'
		})
var changesAssetWindow = new Ext.Window({
	title : '~ Modify Window ~',
	width : 400,
	height : 320,
	modal : true,
	resizable : true,
	closeAction : 'hide',
	items : [updateAssetForm],
	buttons : [{
		iconCls : 'update',
		text : 'Save',
		// disabled : false,
		handler : function() {
			if (!updateAssetForm.getForm().isValid()) {
				return;
			} else {
				updateAssetForm.getForm().submit({
							waitMsg : 'Modifying.....',
							url : '/Shrek/updataAssetServlet', // 访问数据库修改资产表的信息
							// -- 参数 --
							// 除了AssetNo 和
							// state
							// 其他参数都可以更改
							success : function(f, action) {
								changesAssetWindow.hide();
								alert(action.result.msg);
								if (action.result.success) {
									updateAssetForm.getForm().reset();
//									insertUserLog(3); // 修改资产信息成功，记录用户日志 ，1 --
									// XX管理员修改资产信息成功
//									alert('修改成功');
									AssetStore.reload();
									AssetTypeStore.reload();
								} 
								else
//									insertUserLog(4); // 修改资产信息失败，记录用户日志 ，0 --
//								// XX管理员修改资产信息失败
									alert('failed');

							}
						})
			}
		}
	}, {
		iconCls : 'empty',
		text : 'Empty',
		handler : function() {
			updateAssetForm.getForm().reset();
		}
	}, {
		iconCls : 'back',
		text : 'Return',
		handler : function() {
			changesAssetWindow.hide();
		}
	}]
})



var BuildInputForm = function() {
	InputForm = new Ext.form.FormPanel({
				labelAlign : 'right',
				labelWidth : 70,
				width : '100%',
				bodyStyle : 'padding:20px 10px;',
				items : [{
							layout : 'column',
							border : false,
							items : [{
										bodyStyle : 'padding-top:5px',
										columnWidth : .9,
										layout : 'form',
										defaults : {
											width : 130
										},
										defaultType : 'textfield',
										items : [{
													fieldLabel : 'ProductID',
													name : 'assetNo',
													readOnly : true
												},{
													fieldLabel : 'BelongTo',
													name : 'belongTo',
													allowBlank : false
												}]
									}]
						}]
			})
}

var BuildInputWindow = function() {
	InputWindow = new Ext.Window({
				title : '~ Input Window ~',
				width : 300,
				heigth : 500,
				modal : true,
				resizable : false,
				closeAction : 'hide',
				items : [InputForm],
				buttons : [{
							iconCls : 'save',
							text : 'Save',
							handler : function() {
							if (!InputForm.getForm().isValid()) {
									return;
							} else{
								InputForm.getForm().submit({
									waitMsg : 'Modifying.....',
									url : '/Shrek/updataAssetBelongToServlet', // 访问数据库修改资产表的信息
									success : function(f, action) {
										InputWindow.hide();
										alert(action.result.msg);
										if (action.result.success) {
											InputForm.getForm().reset();
//											insertUserLog(3); // 修改资产信息成功，记录用户日志 ，1 --
											// XX管理员修改资产信息成功
//											alert('修改成功');
											AssetStore.reload();
										} 
										else
//											insertUserLog(4); // 修改资产信息失败，记录用户日志 ，0 --
//										// XX管理员修改资产信息失败
											alert('failed');

									}})}
							}
						}],
				buttonAlign : 'center'
			})
}


/*
 * 资产信息成功添加 参数 1 -- 添加成功 2 -- 添加失败 记录用户日志
 */
var insertUserLog = function(flag,record) {
	if (flag == 1) {
		Ext.Ajax.request({
					url : '/Shrek/insertLog',
					success : Ext.emptyFn(),
					failure : Ext.emptyFn(),
					params : {
						data : 1,
//						type : "添加资产登记信息",
						obj : record
					}
				});
		AssetStore.reload();
	} else if (flag == 2) {
		Ext.Ajax.request({
					url : '/Shrek/insertLog',
					success : Ext.emptyFn(),
					failure : Ext.emptyFn(),
					params : {
						data : 0,
//						type : "添加资产登记信息",
						obj : record
					}
				});
	} 
}

var getAssetNo = function() {
	var today = new Date();

	var month = today.getMonth() + 1;
	if (month < 10) {
		month = "0" + month;
	}

	var day = today.getDate();
	if (day < 10) {
		day = "0" + day;
	}

	assetNo = "F" + today.getFullYear() + month + day;

	Ext.lib.Ajax.request('POST', '/Shrek/autoAssetNo', {
				success : function(response, opts) {
					var autoAdd = Ext.util.JSON.decode(response.responseText);
					if (autoAdd < 10)
						assetNo = assetNo + "000" + autoAdd;
					if (autoAdd >= 10 && autoAdd < 100)
						assetNo = assetNo + "00" + autoAdd;
					if (autoAdd >= 100 && autoAdd < 1000)
						assetNo = assetNo + "0" + autoAdd;
					if (autoAdd >= 1000)
						assetNo = assetNo + autoAdd;
					addAssetForm.getForm().reset();
					addAssetForm.form.findField('AssetNo').setValue(assetNo);
				},
				failure : Ext.emptyFn
			});
}
/*
 * 初始化各个界面的布局
 */
var init = function() {
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';

	BuildAssetGrid();
	BuildQueryForm();
	BuildDetailAssetForm();
	// BuildUpdateAssetForm();
	// BuildAddAssetForm();
	BuildDetailAssetWindow();
	BuildQueryWindow();
	BuildInputForm();
	BuildInputWindow();
	BuildLayout();
	
//	alert(namese);
	if(namese == 'guest')
    {
		AssetGridPanel.getTopToolbar().items.get('add').hide();
		AssetGridPanel.getTopToolbar().items.get('delete').hide();  
		AssetGridPanel.getTopToolbar().items.get('edit').hide();  
		AssetGridPanel.getTopToolbar().items.get('save').hide();
		AssetGridPanel.getTopToolbar().items.get('change').hide();
    }
	AssetGridPanel.getTopToolbar().items.get('scan').hide();
	
//	QueryWindow.show();
	autoQuery();
	
}

Ext.onReady(init);